package fyp.spedmew.backend.entity;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.config.Named;
import com.google.api.server.spi.config.Nullable;
import com.google.api.server.spi.response.CollectionResponse;
import com.google.api.server.spi.response.ConflictException;
import com.google.api.server.spi.response.NotFoundException;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.googlecode.objectify.cmd.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import static fyp.spedmew.backend.service.OfyService.ofy;

@Api(name = "checkInEndpoint", version = "v1", namespace = @ApiNamespace(ownerDomain = "entity.backend.spedmew.fyp", ownerName = "entity.backend.spedmew.fyp", packagePath=""))
public class CheckInEndpoint {
    private static final Logger log = Logger.getLogger(CheckInEndpoint.class.getName());

    // Make sure to add this endpoint to your web.xml file if this is a web application.
    public CheckInEndpoint() {

    }

    /**
     * This inserts a new <code>CheckIn</code> object.
     * @param checkIn The object to be added.
     * @return The object to be added.
     */
    public CheckIn insertCheckIn(CheckIn checkIn) throws ConflictException {
        log.info("insertJob called");
        //If if is not null, then check if it exists. If yes, throw an Exception
        //that it is already present
        if (checkIn.getId() != null) {
            if (findRecord(checkIn.getId()) != null) {
                throw new ConflictException("Object already exists");
            }
        }
        //Since our @Id field is a Long, Objectify will generate a unique value for us
        //when we use put
        ofy().save().entity(checkIn).now();
        return checkIn;
    }

    /**
     * This methods find CheckIn by job id
     * @param jobId The job id of the CheckIns to be return.
     */
    public List<CheckIn> findCheckInByJobId(@Named("jobId") Long jobId) throws NotFoundException {
        log.info("findCheckInByJobId jobId " + jobId);
        Job job = ofy().load().type(Job.class).id(jobId).now();
        return ofy().load().type(CheckIn.class).filter("job", job).list();
    }

    /**
     * This method to retrieve a <code>Job</code> record
     */
    public CheckIn findRecord(@Named("id") Long id) {
        return ofy().load().type(CheckIn.class).id(id).now();
    }
}